import BaseFormWidget from './BaseFormWidget.js';
import {
    getOpt
} from "../tools.js";


var template = require('./templates/CheckboxWidget.mustache');
/**
 * Build a Checkbox (a toggle by default)
 * 
 * See documentation of BaseFormWidget for base options
 * 
 * 
 * Widget specific field
 * 
 *  @param string inline_label: The label shown aside the checbox
 *  @param string true_val: The True value (default '1') used when checked
 *  @param string false_val: The False value (default '0') used when unchecked
 *  @param boolean toggle: Is the checkbox show as a toggle (default true)
 * 
 * @fires finishEventName - field_name, value
 * @fires finishEventName:field_name - field_name, value
 *
 */

const CheckboxWidget = BaseFormWidget.extend({

    template: template,
    ui: {
        checkbox: 'input[type=checkbox]'
    },
    events: {
        'click @ui.checkbox': 'onClick'
    },
    getCurrentValue: function () {
        var checked = this.getUI('checkbox').prop('checked');
        if (checked) {
            return getOpt(this, 'true_val', '1');
        } else {
            return getOpt(this, 'false_val', '0');
        }
    },
    onClick: function (event) {
        const field_value = this.getCurrentValue();
        this.triggerFinish(field_value);
    },
    templateContext: function () {
        let result = this.getCommonContext();
        var true_val = getOpt(this, 'true_val', '1');
        var checked = this.getOption('value') == true_val;
        let divCss = "checkbox";
        if (getOpt(this, 'toggle', true)) {
            divCss = "toggle";
        }
        let others = {
            inline_label: getOpt(this, 'inline_label', ''),
            checked: checked,
            divCss: divCss,
        };
        return Object.assign(result, others);
    }
});
export default CheckboxWidget;